package cn.seaboot.excel.tools;

import cn.seaboot.commons.core.Asserts;
import cn.seaboot.excel.ExcelBook;
import cn.seaboot.excel.header.Header;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
import org.jetbrains.annotations.NotNull;

/**
 * 水印的功能，要求 Excel 版本必须在 2007 之上
 *
 * @author Mr.css
 * @version 2025-03-26 11:18
 */
public class CommentTools extends Tools {

    public CommentTools(ExcelBook book) {
        super(book);
    }

    /**
     * 写入一个带批注的表头
     *
     * @param row     行号
     * @param headers 表头
     * @since Excel 2007
     */
    public void writeHeader(int row, @NotNull Header[] headers) {
        XSSFSheet st = book.getXSSFSheet();
        XSSFRow r = st.createRow(row);
        XSSFDrawing drawing = st.createDrawingPatriarch();
        // 写入数据
        for (int i = 0; i < headers.length; i++) {
            Header header = headers[i];
            XSSFCell c = r.createCell(i);
            // style
            c.setCellStyle(book.getStyle());
            // value
            c.setCellValue(header.getLabel());

            // comment
            if (header.getComment() != null) {
                XSSFComment comment = drawing.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, 0, 0, 0, 0));
                comment.setString(header.getComment());
                c.setCellComment(comment);
            }
        }
    }

    /**
     * 制作单元格批注
     * <p>
     * 前置要求：单元格必须已经存在
     *
     * @param row     行号
     * @param col     列号
     * @param comment 批注
     * @since Excel 2007
     */
    public void comment(int row, int col, String comment) {
        XSSFSheet st = book.getXSSFSheet();

        Row xssfRow = st.getRow(row);
        Asserts.notNull(xssfRow, "cell is undefined: [{}, {}]", row, col);

        Cell xssfCell = xssfRow.getCell(col);
        Asserts.notNull(xssfCell, "cell is undefined: [{}, {}]", row, col);

        XSSFDrawing drawing = st.createDrawingPatriarch();
        XSSFComment cellComment = drawing.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, 0, 0, 0, 0));
        cellComment.setString(comment);

        xssfCell.setCellComment(cellComment);
    }
}
